<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <!--{include file='comm/header.tpl'}-->
    	<title>用户筛选器</title>
    <!--{include file='comm/comm_pic.tpl'}-->
    <!--{include file="comm/icheck.tpl"}-->
</head>
<body>
<div style="width:100%">
    <div class="items clearfix">
        <h2 style="" class="tal">
        	正在操作：
        	<!--{if !isset($selectorInfo)}-->添加<!--{else}-->修改<!--{/if}-->用户筛选器
        </h2>
        <div class="items2">
			<div>
                <form id="selector_form" class="form-horizontal" onsubmit="return false;">

                    <div class="form-group">
                        <label class="col-sm-3 control-label" for="selectName">
                            <span class="red">*</span>
                            筛选器名称：
                        </label>
                        <div class="col-sm-9">
                            <input type="text" class="form-control w300" name="selectName" id="selectName" value="<!--{$selectorInfo->selectDisplayName|default:''}-->">
                            <input type="hidden" name="selectID" id="selectID" value="<!--{$selectorInfo->selectID|default:''}-->">
                            <input type="hidden" name="dataCache" id="dataCache">
                        </div>
                    </div>



                    <div class="form-group">
                        <label class="col-sm-3 control-label" for="rankID">
                            用户等级：
                        </label>
                        <div class="col-sm-9">
                            <!--{if isset($rankData)}-->
                            <!--{foreach from=$rankData key=k name=n item=rank}-->
                            <!--{if $smarty.foreach.n.index % 4 == 0}-->

                            <!--{/if}-->
									<span style="margin-bottom:22px;display:inline-block;">
										<input type="checkbox" class="square-radio" name="rankID" class='rankID' title="<!--{$rank->rankName}-->" value="<!--{$rank->rankID}-->" />
										<!--{$rank->rankName}-->
									</span>
                            &nbsp;
                            <!--{/foreach}-->
                            <!--{/if}-->

                            <input type="button" onclick="selector.rankAdd();" class="btn" value="添加" style="">
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-3 control-label" for="rankRuleFlg_1">
                            使用规则：
                        </label>
                        <div class="col-sm-9">
                            <input type="radio" value='1'  class="square-radio" name='rankRuleFlg' id="rankRuleFlg_1" checked />包含
                            <input type="radio" value='0' class="square-radio" name='rankRuleFlg' id="rankRuleFlg_0" style="margin-left:10px;" />排斥
                        </div>
                    </div>

                    <div class="form-group">
                        <label class="col-sm-3 control-label" for="description">
                            描述：
                        </label>
                        <div class="col-sm-9">
                            <textarea style="height:80px;padding-left:10px;" name="description" id="description" class="form-control" placeholder="请输入描述"><!--{$selectorInfo->description|default:''}--></textarea>
                        </div>
                    </div>

                    <div id="goodsSelector" style="width:900px;margin: 0 auto;">
						<table id="flex" style="width:100%;padding-bottom:0px;"></table>
					</div>
                </form>
            </div>
        </div>
    </div>

    <div class="bottom_fixbox">
        <div class="rectbox tac">
            <input type="button" class="btn" onclick="selector.check();" value="<!--{if !isset($selectorInfo)}-->添加<!--{else}-->修改<!--{/if}-->筛选器" />
            &nbsp;&nbsp;&nbsp;
            <input type="button" class="btn" onclick="E.closeWindows();" value="关闭" />
        </div>
    </div>


</div>
<script type="text/javascript">
	//表格对象
	var table_obj = { 'page' : '', 'total' : '', 'rows' : []};
	
	$("#flex").flexigrid({
        url:"",
        dataType: "json",
        colModel : [
            {display: "选择器", width:478 , },
            {display: "类型", width:172 , },
            {display: "使用法则", width:172 , }
        ],
        buttons : [
            {name: "删除", bclass: "delete", onpress : "selector.removeRow"}
        ],
        useRp: false,
        showTableToggleBtn: true,
        height:100
    });

    $('.square-radio').iCheck({
        checkboxClass: 'icheckbox_square-blue',
        radioClass: 'iradio_square-blue',
        increaseArea: '20%' // optional
    });

    var selector = {
    	//添加用户等级筛选规则
        rankAdd : function(){
        	var rankLength = $('[name=rankID]:checked').length;
        	if(rankLength <= 0){
        		E.alert('请选择用户等级');
        		return false;
        	}
        	
        	var rankStr  = '';
        	var rankText = '';
        	$.each($('[name=rankID]:checked'), function(k, v){
        		rankStr += ',' + $(this).val();
        		rankText += ' | ' + $(this).attr('title');
        	})
        	
        	//用户等级字符串
        	rankStr  = rankStr.substr(1);
        	rankText = rankText.substr(2);
        	
        	//排斥规则
        	var rankRuleFlg = $('[name=rankRuleFlg]:checked').val();
        	var ruleText = '';
        	if(rankRuleFlg == 1)
        		ruleText = '包含';
        	else
        		ruleText = '排斥';	
 
        	//保存dataCache数据
        	var data = [1, rankStr, rankRuleFlg];
        	
        	var rankObj = $('#dataCache').data('rank');
        	if(!rankObj)
        		rankObj = {};
        		
        	rankObj['rank'] = data;
        	$('#dataCache').data('rank', rankObj);
        	
        	//生成行数据
        	this.tr_fun('rank', [rankText, '用户等级', ruleText]);
        },
        
         //添加一行
		 tr_fun : function(id, value){
		 	
		 	table_obj.rows.splice(id);

			table_obj.rows.push({'id' : id, 'cell' : value});
        	
        	$("#flex").flexAddData(table_obj);	
			
			var cache = $('#dataCache').data('rank');
			console.log(cache);
        },
        
        //查询用户
        userCheck : function(){
        	var custName = $.trim($('#custName').val());
        	if(custName == '' || custName == null){
        		E.alert('请输入用户名');
        		$('#allSource').html('');
        		return false;
        	}
        	
        	var userName = {userName : custName};
        	$.ajax({
        		type: "POST",
                url : '/invokingAjax-backend/promotion/userSelector.ajax?operFlg=4',
                dataType: "JSON",
                data: userName,
                success: function( result_obj ) {
                    if (result_obj.code == 200){
                       if(result_obj.message != null){
                       		option_html = '';
                       		$.each(result_obj.message, function(k, v){
                       			option_html += '<option value=' + k + '>' ;
								option_html += v;
								option_html += '</option>' ;
                       		})
                       		
							$('#allSource').html(option_html);
                       }
                    }else
                        E.alert(result_obj.message);
                }
        	})
        },
        
        //向右移动
        rightMv_fun : function(flg){
        	if(flg == 0)
				var mvValue = $("#allSource").val();	//已选中的值
			else
				var mvValue = $("#allSource option");	//所有的值

			var mvLen = 0;
			if(mvValue)
				mvLen = mvValue.length;
			
			var option_Str = $("#publishSource").html();
			for(var i=0; i<mvLen; i++){
				if(flg == 0)
					var val = mvValue[i];
				else
					var val = mvValue[i].value;

				var rightText = $("#publishSource option[value='" + val + "']").text();
				if(rightText == ""){
					var mvText = jQuery.trim($("#allSource option[value='" + val + "']").text());
					option_Str += "<option value=" + val + ">" ;
					option_Str += mvText;
					option_Str += "</option>" ;
				}
			}
			
			$("#publishSource").html(option_Str);
        },
        
        //向左移动
        leftMv_fun : function(flg){
        	if(flg == 0)
				var val = $("#publishSource").val();
			else
				var val = $("#publishSource option");
			
			if(val)
				var val_len = val.length;
			
			for(var i = 0;i < val_len;i++){
				if(flg == 0)
					$("#publishSource option[value='" + val[i] + "']").remove();
				else{
					var mv_val = val[i].value;
					$("#publishSource option[value='" + mv_val + "']").remove();
				}
			}
        },
        
        //检查数据
        check: function() {
            this.dt = E.getFormValues('selector_form');
            var error_msg = '';
            if (this.dt.selectName == '')
                error_msg += "筛选器名称不能为空<br />";
                
            var rankObj = $('#rowrank').length;
            var publishSource = $('#publishSource').html();

            if(rankObj <= 0 && publishSource == '')
            	error_msg += "请添加用户筛选规则<br />";
                
            if (error_msg != "")
                E.alert(error_msg);
            else
                E.confirm("您确认要<!--{if isset($selectorInfo)}-->修改<!--{else}-->添加<!--{/if}-->筛选器信息吗？", "selector.add");
        },

        //保存资源位信息
        add: function() {
        	//判断添加还是编辑
        	var selectID = $.trim($('#selectID').val());
        	
        	//传输参数
        	var data = [];
        	
        	//获取用户名筛选
        	var publishSource = '';
        	$.each($('#publishSource option'), function(k, v){
        		publishSource += ',' + $(v).text();
        	})
        	publishSource = publishSource.substr(1);
        	
        	ruleFLg = $('[name=userRuleFlg]:checked').val();
        	
        	if(publishSource != '' && publishSource != null)
        		data.push([2, publishSource, ruleFLg]);
        	
        	var rankObj = $('#dataCache').data('rank');
        	if(rankObj)	
        		data.push(rankObj['rank']);
        		
        	var selectorData = {dt : this.dt, rule : data};
            $.ajax({
                type: 'POST',
                url: '/invokingAjax-backend/promotion/userSelector.ajax?operFlg=2',
                dataType: "JSON",
                data: selectorData,
                success: function( result_obj ) {

                    if (result_obj.code == 200 && selectID != ''){
                        E.alert(result_obj.message, 2, 'E.closeWindows');
                        E.opener('selector.load');
                    }else if(result_obj.code == 200 && selectID == ''){
						E.alert(result_obj.message, 2, 'E.refresh');  
						E.opener('selector.load'); 
                    }else
                        E.alert(result_obj.message);
                }
            });
        },
        
        //删除行信息
        removeRow : function(){
        	var rankRow = $('#rowrank').hasClass('trSelected');
        	if(rankRow){
        		//清空对象数组数据
        		table_obj.rows = [];
        		
        		//删除选中的行
        		$('#rowrank').remove();
        		
        		//删除dataCache数据
        		var rankObj = $('#dataCache').data('rank');
        		if(rankObj)
        			delete rankObj['rank'];
        		
        	}else
        		E.alert('请选择需要删除的选择器');
        },

        
    };

    //编辑初始化显示选择器
    $(document).ready(function() {
		<!--{if isset($selectorRule)}-->
			<!--{foreach from=$selectorRule item=rule}-->
				var selectType = <!--{$rule->selectType}-->;
				if(selectType == 1){	//等级
					//生成行数据
					var ruleText = 0;
					var ruleFLg = <!--{$rule->ruleFLg}-->;
					if(ruleFLg == 1)
						ruleText = '包含';
					else
						ruleText = '排斥';	

					var value = ['<!--{$rule->selectorText}-->', '用户等级', ruleText]
					selector.tr_fun('rank', value);
					
					//添加dataCache
					var rankObj = $('#dataCache').data('rank');
					if(!rankObj)
						rankObj = {};
						
					rankObj['rank'] = [<!--{$rule->selectType}-->, '<!--{$rule->selector}-->', <!--{$rule->ruleFLg}-->];	
					$('#dataCache').data('rank', rankObj);
					
					var ruleFLg = <!--{$rule->ruleFLg}-->;
					if(ruleFLg == 1)
						$('#rankRuleFlg_1').attr('checked', true);
					else
						$('#rankRuleFlg_0').attr('checked', true);
					
				}else if(selectType == 2){	//客户
					var optionArray = '<!--{$rule->optionArray}-->';
					optionArray = eval('(' + optionArray + ')');
					var option_Str = '';
					$.each(optionArray, function(k, v){
						option_Str += "<option value=" + k + ">" ;
							option_Str += v;
						option_Str += "</option>" ;
					})
			
					$("#publishSource").html(option_Str);
					
					var ruleFLg = <!--{$rule->ruleFLg}-->;
					if(ruleFLg == 1)
						$('#userRuleFlg_1').attr('checked', true);
					else
						$('#userRuleFlg_0').attr('checked', true);
				}
			<!--{/foreach}-->
		<!--{/if}-->
    });
</script>

</body>

</html>
